layui.define(['layer','helper','table', 'parsedata', 'form', 'laydate'], function (exports) {
	window.$ = layui.$;
	var table = layui.table;
	window.table = table;
	var parsedata = layui.parsedata;
	var form = layui.form;
	var laydate = layui.laydate;
	var openWidth = getPageWidth() < 960 ? '100%' : '80%';
	var obj = {	
		
		//表格
		layuiTable: function(url, id, menuData){
			let primaryKey = menuData.table_struct.primary_key;
			let colsData = [];
			if(menuData.detail && $_GET['fun'] == undefined){
				colsData.push({fixed: 'left', width:60, align:'center', toolbar: '#leftbarDemo',title:'<i class="layui-icon layui-icon-spread-left"></i>'});
			}
			
			if($_GET['fun'] && strrpos($_GET['fun'], 'one') >= 0){
				colsData.push({type:'radio'});
			}else{
				colsData.push({type:'checkbox'});
			}
			
			for(i in menuData.table_struct.field){
				var obj = menuData.table_struct.field[i];
				if(obj.in_list === true){
					colsData.push({field: i, title: obj['label'], width: obj['width'], sort: true});
				}
			}
			colsData.push({fixed: "right",width: menuData.operate_width,align:'center', toolbar: '#barDemo',title:'操作'});
			//表格渲染
			table.render({
				elem: '#'+id
				,url:url
				,toolbar: '#toolbarDemo'
				,defaultToolbar:['filter', 'print', 'exports',{
					title: '刷新'
				  ,layEvent: 'RELOAD'
				  ,icon: 'layui-icon-refresh'
				}]
				,cols: [colsData]
				,page: {
				    	groups : 5,
				    	last : false,
				    	layout: ['prev', 'page', 'next', 'limit', 'count']
				},
				size: 'lg',
				parseData: function(res){ //将原始数据解析成 table 组件所规定的数据
					$("#dataNum").html(res.data.total);
					let itemdata = res.data.data;
					let field = memuData.table_struct.field;
					//需要处理的有图片 时间戳  image, datetime
					var selected = [];
					if($_GET['selected']){
						selected = explode(',' ,$_GET['selected']);
					}
					for(i in itemdata){
						//开始解析数据
						var items = itemdata[i];
						for(ii in items){
							try{
								var parseFun = field[ii]['input_type'];
								var parseOption = field[ii]['value'];
							}catch(e){
								var parseFun = 'text';
								var parseOption = [];
							}
							
							//数组value是关联数组的情况
							try{
								if(parseOption[0]['key']){
									var selectOptions = new Array();//这里就不管他妈的索引不索引的了会排序但不会丢失索引
									for(psi in parseOption){
										var rowOption = parseOption[psi];
										selectOptions[rowOption.key] = rowOption.val;
									}
									parseOption = selectOptions;
								}
							}catch(e){
								//TODO handle the exception
							}
							//、、
							var item =  items[ii];	
							if(is_object(item)){
								item = json_encode(item);
							}
							eval('item = parsedata.'+parseFun+'(item, parseOption);');
							if(in_array(ii, ['create_time', 'update_time']) && is_numeric(item) && item > 0 && parseFun == 'hidden'){
								item = formatDate(item * 1000, 'Y-M-D H:i:s');
							}
							itemdata[i][ii] = item;
						}
						if(in_array(itemdata[i][primaryKey], selected)){
							itemdata[i]['LAY_CHECKED'] = true;
						}
						
					}
				  return {
					  "code": res.errorcode, //解析接口状态
					  "msg": res.errormsg, //解析提示文本
					  "count": res.data.total, //解析数据长度
					  "data": itemdata //解析数据列表
				  };
				}
		    });
			
			
			//头工具栏事件
			  table.on('toolbar('+id+')', function(obj){
			    var checkStatus = table.checkStatus(obj.config.id);
			    switch(obj.event){
			      case 'add':
					  var addPage = './finder/add.html';
					  if(!empty(window.memuData.custom_tempadd)){
						addPage = window.memuData.custom_tempadd;
					  }
					  var _method_ = '';
					  if($(this).data('href')){
						  _method_ = $(this).data('href');
					  }
					  var href = addPage+'?api='+$_GET['api']+'&_method_='+_method_+'&toolbar=head';
					  layer.open({
						  type: 2,
						  title: "添加",
						  shadeClose: true,
						  shade: 0.5,
						  offset:'r',
						  scrollbar: false,
						  area: [openWidth, '100%'],
						  content: href, //iframe的url
						  cancel: function(){
							  if(window.toRefresh == true){
								  window.location.reload();
							  }
						  }
					  }); 
			      break;
			      case 'open':
				  layer.open({
					  type: 2,
					  title: $(this).data("title"),
					  shadeClose: true,
					  shade: 0.7,
					  offset:'r',
					  scrollbar: false,
					  area: [openWidth, '100%'],
					  content: $(this).data("href")+"?toolbar=head"
				  });
			      break;
			      case 'submit':
				    var data = checkStatus.data;
					if(data == false) return noticeMsg("error", "请选择需要"+$(this).data("title")+"的数据");
					if($(this).data("href") == false)  return noticeMsg("error", "href地址未配置");
					var _method_ = $(this).data("href");
					layer.confirm('确定要'+$(this).data("title")+"?", function(index){
					    layer.closeAll();
						var where = '_method=POST&toolbar=head&';
						for(i in data){
						  where += primaryKey+'[]='+data[i][primaryKey]+'&';
						}
						if(strrpos(_method_, '/') >= 0){
							ajax_request(_method_, 'POST', where, function(res){
							try{
								if(res.errorcode == 0){
									noticeMsg("success", res.errormsg);
									table.reload(id);
								}
							}catch(e){
								layer.msg(res);
							}
						});
						}else{
							ajax_request($_GET['api']+"?_method_="+_method_, 'POST', where, function(res){
							try{
								if(res.errorcode == 0){
									noticeMsg("success", res.errormsg);
									table.reload(id);
								}
							}catch(e){
								layer.msg(res);
							}
						});
						}  
					});
			      break;
			      case 'delete':
			        //批量删除
					var data = checkStatus.data;
					if(data == false) return noticeMsg("error", "请选择需要"+$(this).data("title")+"的数据");
		  
					layer.confirm('确定要'+$(this).data("title")+"?", function(index){
					  layer.closeAll();
					  var where = '_method=DELETE&';
					  for(i in data){
					    where += primaryKey+'[]='+data[i][primaryKey]+'&';
					  }
					  ajax_request($_GET['api'], 'POST', where, function(res){
						    layer.closeAll();
							var code = res.errorcode;
							if(code == 0){
								//全选的删除是要刷新的
								if(checkStatus.isAll == true){
									window.location.reload();
								}else{
									$(".layui-form-checked").each(function(i){
										var myObj = $(this).parent().parent().parent();
										for(ii in data){
											if(data[ii][primaryKey] == myObj.find('.layui-table-cell').eq(1).html()){
												myObj.remove();
												//删除行
											}
										}
								  });
								}
								//删除完成
								//关闭当前窗口
		  
								//获取一下当前行数
								if($(".layui-table").eq($(".layui-table").length - 1).find('tr').length <= 0){
									//触发页面刷新
									window.location.reload();
								}
							}else{
								return noticeMsg("error", "删除失败");
							}
					  });
						
					});
			      break;
			      
			      //自定义头工具栏右侧图标 - 提示
			      case 'RELOAD':
			          window.location.reload();
			      break;
			    	
			    };
			  });
			  
			  //监听行工具事件
			table.on('tool(test)', function(obj){
			  window.selectObj = obj;
			  var data = obj.data;
			  if(obj.event === 'delete'){
				layer.confirm('确定要'+$(this).data("title")+"?", function(index){
				  layer.close(index);
				  layerTableRowDelete($_GET['api']+'?_method=DELETE&'+primaryKey+'='+data[primaryKey], obj);//执行删除
				});
			  } else if(obj.event === 'edit'){
			    var editPage = './finder/edit.html';
			    if(!empty(window.memuData.custom_tempedit)){
					editPage = window.memuData.custom_tempedit;
			    }
				var _method_ = '';
				if($(this).data('href') != false){
				   _method_ = $(this).data('href');
				}
			    var href = editPage+'?api='+$_GET['api']+'&_method_='+_method_+'&toolbar=row&'+primaryKey+'='+data[primaryKey];
				layer.open({
				  type: 2,
				  title: $(this).data("title"),
				  shadeClose: true,
				  shade: 0.2,
				  scrollbar: false,
				  offset:'r',
				  area: [openWidth, '100%'],
				  content: href, //iframe的url
				}); 
			  }else if(obj.event === 'open'){
				layer.open({
					  type: 2,
					  title: $(this).data("title"),
					  shadeClose: true,
					  scrollbar: false,
					  shade: 0.2,
					  offset:'r',
					  area: ['50%', '100%'],
					  content: $(this).data("href")+'?'+primaryKey+'='+data[primaryKey], //iframe的url
					}); 
			  }else if(obj.event === 'submit'){
				  if($(this).data("href") == false)  return noticeMsg("error", "href地址未配置");
					var _method_ = $(this).data("href");
					layer.confirm('确定要'+$(this).data("title")+"?", function(index){
						layer.closeAll();
						var where = '_method=POST&';
						where += primaryKey+'[]='+data[primaryKey]+'&';
						if(strrpos(_method_, '/') >= 0){
							ajax_request(_method_, 'POST', where, function(res){
								try{
									if(res.errorcode == 0){
										noticeMsg("success", res.errormsg);
										table.reload(id);
									}
								}catch(e){
									layer.msg(res);
								}
							});
						}else{
							ajax_request($_GET['api']+"?toolbar=row&_method_="+_method_, 'POST', where, function(res){
								try{
									if(res.errorcode == 0){
										noticeMsg("success", res.errormsg);
										table.reload(id);
									}
								}catch(e){
									layer.msg(res);
								}
							});
						}
					  
				  });
			  }else if(obj.event === 'spread'){
				selectDetails(this, data[primaryKey]);
				//primaryKey+'='+data[primaryKey]
			  }else{
				layer.msg("row_toolbar自定义event目前只支持"+"add,delete,open,submit", {
					icon : 2,time:3000,shift: 6
				});
			  }
			});
		}
	};
	window.layerTableRowDelete = function(url, obj){
		ajax_request(url, "POST", "", function(res){
			layer.closeAll();
			var code = res.errorcode;
			if(code == 0){
				noticeMsg("success", "删除成功");
				obj.del();
				//关闭当前窗口
			
				//获取一下当前行数
				if($(".layui-table").eq($(".layui-table").length - 1).find('tr').length <= 0){
					//触发页面刷新
					window.location.reload();
				}
			}else{
				return noticeMsg("error", "删除失败");
			}
		});
	}
	
	
	window.lineSo = function(obj){
		if($("#linesoval").val() == ''){
			setcookie($_GET['api']+'_so', '', 0);
			window.location.reload();
			return;
		}else if($("#linesokey").val() == memuData.table_struct.primary_key){
			//如果带，应该是in查询
			var condition = '=';
			if(strrpos($("#linesoval").val(), ',') >= 0){
				condition = 'IN';
			}
			var json = [[$("#linesokey").val(),condition,window.btoa(encodeURI($("#linesoval").val()))]];
		}else{
			var json = [[$("#linesokey").val(),'LIKE',window.btoa(encodeURI('%'+$("#linesoval").val()+'%'))]];
		}
		setcookie($_GET['api']+'_so', JSON.stringify(json), 3600*24);
		window.location.reload();
	}

	window.cleanSearch = function(obj){
		setcookie($_GET['api']+'_so', '', 0);
		window.location.reload();
	}
	
	var selectDetailsObj = null;
	var selectDetailId = null;
	window.selectDetails = function(obj, id){
		selectDetailId = id;
		if(selectDetailsObj != null) $(selectDetailsObj).html('&#xe602;');
		selectDetailsObj = obj;
		$(obj).html('&#xe61a;');
		$("#tx_div").css('display','');
		$("#tx_div").css('top',$(obj).offset().top+35);
		// $(document.body).css({  
	 //        "overflow": "hidden"  
	 //    }); 
		$('.layui-table-main').css({  
	        "overflow": "hidden"  
	    }); 
	    //点击第一个
	    $("#detail-ul").find('li').eq(0).click();
	}
	window.detailsColse = function(){
		$(selectDetailsObj).html('&#xe602;');
		$("#tx_div").css('display','none');
		$(document.body).css({  
			"overflow": "auto"  
		});  
		$('.layui-table-main').css({  
	            "overflow": ""  
		}); 
	}
	var ajaxDetailData = {};
	window.ajaxDetail = function(obj, fun){
		$("#detail-ul").find('li').each(function(index){
			$(this).removeClass('layui-this');
		});
		$(obj).addClass('layui-this');
		
		if(ajaxDetailData[fun+selectDetailId]){
			$("#finder-content").html(ajaxDetailData[fun+selectDetailId]);
			return;
		}
		
		ajax_request($_GET['api']+'?_method=detail&method='+fun+'&'+memuData.table_struct.primary_key+'='+selectDetailId, 'POST', '', function(res){
			$("#finder-content").html(res);
			ajaxDetailData[fun+selectDetailId] = res;
		});
	}
		
	
	window.showSearchInfo = function(){
		if($("#linesokey").find('option').length > 0){
			$("#so-form").css("display","");
		}
		var socookie = getcookie($_GET['api']+'_so');
		if(socookie){
			try{
				socookie = eval('('+socookie+')');
				if(socookie.length == 1){
					$("#linesokey").find('option').each(function(index){
						if(this.value == socookie[0][0]){
							$(this).attr("selected",true);
							var val = socookie[0][2];
							rv = window.atob(val);
							rv = escape(rv);
							rv = decodeURI(decodeURIComponent(rv));
							rv = str_replace(['%'], [''], rv);
							$("#linesoval").val(rv);
						}
					});
				}
			}catch(e){
				console.error(socookie);
			}
			
			$("#searchInfo").css("display", '');
		}
	}
	window.advancedso = function(obj){
		layer.open({
		  type: 2,
		  title: "高级搜索",
		  shadeClose: true,
		  scrollbar: false,
		  shade: 0.2,
		  offset:'r',
		  area: [getRatioWidth(0.2, 350)+'px', '100%'],
		  content: './finder/search.html', //iframe的url
		});
	}

	// 搜索
	$('#btnSearch').click(function () {
		var keywords = $('#edtSearch').val();
		if (keywords) {
			insTb.filterData(keywords);
		} else {
			insTb.clearFilter();
		}
	});

	// 清除搜索
	$('#btnClearSearch').click(function () {
		insTb.clearFilter();
	});	
	
	
	exports('finder', obj);//导出
});